//
//  ToolButton.m
//  sHome
//
//  Created by tracyhenry on 09/01/2018.
//  Copyright © 2018 Siterwell. All rights reserved.
//
#define RGBA(r,g,b,a) [UIColor colorWithRed:r/255.0f green:g/255.0f blue:b/255.0f alpha:a]
#define RGB(r,g,b) RGBA(r,g,b,1.0f)
#define SYSTEMFONT(FONTSIZE)     [UIFont systemFontOfSize:FONTSIZE]
#define NormalColor RGB(70,221,140)
#define AlarmColor RGB(255,0,0)

#import "ToolBox.h"
#import "DebugViewCell.h"
#import <Masonry/Masonry.h>
#import "NVLogManager.h"

static ToolBox *box;

@interface ToolBox ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIButton *cancelButton;

@property (nonatomic, strong) UIButton *clearButton;

@property (nonatomic, strong) UIView *vheader;

@property(nonatomic,strong) UITableView *table;

@property (nonatomic, strong) UIPanGestureRecognizer *panGesture;


@property (nonatomic, strong) NSMutableArray<DebugInfo*> *arrary;

@property(nonatomic,assign) BOOL currentIsInBottom;
@end


@implementation ToolBox

+ (instancetype)sharedToolBox {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        box = [[ToolBox alloc] initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width*1/3,
                                                        50,
                                                        [UIScreen mainScreen].bounds.size.width*2/3, [UIScreen mainScreen].bounds.size.height/2)];
    });
    
    return box;
}


#pragma mark -

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self.layer setMasksToBounds:YES];
        self.backgroundColor = [UIColor colorWithRed:35/255.0
                                               green:35/255.0
                                                blue:35/255.0
                                               alpha:0.6];
        self.currentIsInBottom = YES;
        _vheader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, 50)];
        [_vheader setBackgroundColor:[UIColor blackColor]];
        [self addSubview:_vheader];
        
        _cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelButton.frame = CGRectMake(12, 57, 24, 24);
        [_vheader addSubview:_cancelButton];
        [_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.left.mas_equalTo(5);
        }];
        
        NSURL *bundleURL = [[NSBundle bundleForClass:[ToolBox class]] URLForResource:@"ToolBox" withExtension:@"bundle"];
        NSBundle *bundle = [NSBundle bundleWithURL:bundleURL];
        [_cancelButton setImage:[UIImage imageNamed:@"close" inBundle:bundle compatibleWithTraitCollection:nil]
                            forState:UIControlStateNormal];
        [_cancelButton addTarget:self
                     action:@selector(goCancel)
           forControlEvents:UIControlEventTouchUpInside];
        
        
        _clearButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _clearButton.frame = CGRectMake(12, 57, 24, 24);
        [_clearButton setImage:[UIImage imageNamed:@"clearall" inBundle:bundle compatibleWithTraitCollection:nil]
                            forState:UIControlStateNormal];
        [_clearButton addTarget:self action:@selector(goClearAll) forControlEvents:UIControlEventTouchUpInside];
        [_vheader addSubview:_clearButton];
        [_clearButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(0);
            make.right.mas_equalTo(-5);
        }];
        
        
        _table= [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {_table.sectionHeaderTopPadding=0;}
        _table.dataSource = self;
        _table.delegate = self;
        _table.rowHeight = 65;
        _table.separatorInset = UIEdgeInsetsZero;
        _table.backgroundColor = RGBA(255, 255, 255, 0.0f);
        _table.tableFooterView = [[UIView alloc] init];
        _table.bounces = NO;
        [self addSubview:_table];
        [_table mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.vheader.mas_bottom);
            make.left.mas_equalTo(0);
            make.right.mas_equalTo(0);
            make.bottom.mas_equalTo(self.mas_bottom);
        }];
        
        
        //使用拖动手势，用来支持拖动改变控件位置
        self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self
                                                                  action:@selector(changePostion:)];
        
        [self addGestureRecognizer:self.panGesture];
    }
    
    return self;
}


#pragma mark -

-(void)changePostion:(UIPanGestureRecognizer *)pan {
    CGPoint point = [pan translationInView:self];
    
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    CGFloat height = [UIScreen mainScreen].bounds.size.height;
    
    CGRect originalFrame = self.frame;
    if (originalFrame.origin.x >= 0 && originalFrame.origin.x + originalFrame.size.width <= width) {
        originalFrame.origin.x += point.x;
    }
    
    if (originalFrame.origin.y >= 0 && originalFrame.origin.y + originalFrame.size.height <= height) {
        originalFrame.origin.y += point.y;
    }
    
    self.frame = originalFrame;
    
    [pan setTranslation:CGPointZero inView:self];
    
    if (pan.state == UIGestureRecognizerStateBegan) {
        //_button.enabled = NO;
    } else if (pan.state == UIGestureRecognizerStateChanged){
        
    } else {
        CGRect frame = self.frame;
        //记录是否越界
        BOOL isOver = NO;
        if (frame.origin.x < 0) {
            frame.origin.x = 0;
            isOver = YES;
        } else if (frame.origin.x + frame.size.width > width) {
            frame.origin.x = width - frame.size.width;
            isOver = YES;
        }
        
        if (frame.origin.y < 0) {
            frame.origin.y = 0;
            isOver = YES;
        } else if (frame.origin.y + frame.size.height > height) {
            frame.origin.y = height - frame.size.height;
            isOver = YES;
        }
        
        if (isOver) {
            [UIView animateWithDuration:0.3 animations:^{
                self.frame = frame;
            }];
        }
        
    }
}


#pragma mark - Handling UIButton Events

- (void)goClearAll {
    if (self.clearHandler) {
        self.clearHandler();
    }
}




- (void)goCancel {
    if (self.cancelHandler) {
        self.cancelHandler();
    }
}


#pragma mark -uiTableview delegate
- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
        NSString *cellId = @"cell";
        DebugViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (!cell) {
            cell = [[DebugViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellId];
        }
        
        cell.backgroundColor = RGBA(255, 255, 255, 0.0f);
        DebugInfo *info = [self.arrary objectAtIndex:indexPath.row];
        if(info.isSend){
            [cell.signalBtn setBackgroundColor:NormalColor];
            [cell.signalBtn setTitle:@"S" forState:UIControlStateNormal];
        }else{
            [cell.signalBtn setBackgroundColor:AlarmColor];
            [cell.signalBtn setTitle:@"R" forState:UIControlStateNormal];
        }
        
        if(info.isUDP){
            [cell.tcpBtn setBackgroundColor:[UIColor blueColor]];
            [cell.tcpBtn setTitle:@"UDP" forState:UIControlStateNormal];
        }else{
            [cell.tcpBtn setBackgroundColor:[UIColor greenColor]];
            [cell.tcpBtn setTitle:@"TCP" forState:UIControlStateNormal];
        }
        
        cell.timeLabel.text = info.time;
        cell.contentLabel.text = info.content;
        return cell;
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    DebugInfo *info = [self.arrary objectAtIndex:indexPath.row];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = info.content;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [[UIView alloc] init];

}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [[UIView alloc] init];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.arrary.count;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    DebugInfo *info = [self.arrary objectAtIndex:indexPath.row];
    NSString *str = info.content;
    CGRect rect = [str boundingRectWithSize:CGSizeMake(self.frame.size.width - 16, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: SYSTEMFONT(14)} context:nil];
    
    return rect.size.height+35;
}


// scrollview 减速停止(为了专注于某条日志的悬停，停止刷新时滚动到底部处理)
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
  NVLogInfo(@"scrollViewDidEndDecelerating");
    CGFloat height = scrollView.frame.size.height;
    CGFloat contentOffsetY = scrollView.contentOffset.y;
    CGFloat bottomOffset = scrollView.contentSize.height - contentOffsetY;
    if (bottomOffset <= height)
    {
        //在最底部
        self.currentIsInBottom = YES;
    }
    else
    {
        self.currentIsInBottom = NO;
    }
}

#pragma mark -lazy
-(NSMutableArray *)arrary{
    if(_arrary==nil){
        _arrary = [[NSMutableArray alloc] init];
    }
    return _arrary;
}

#pragma mark -method
-(void)addDebugLog:(DebugInfo *)info{
    [self.arrary addObject:info];
    [self.table reloadData];
    if(self.currentIsInBottom){
        [self.table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.arrary.count-1 inSection:0]  atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }

}

-(void)clearData{
    [self.arrary removeAllObjects];
    self.currentIsInBottom = YES;
    [self.table reloadData];
}

-(void)dealloc {
    self.arrary = nil;
    self.table = nil;
}
@end
